import React, { ReactElement, useEffect, useContext, useState } from 'react';
import { RefreshControl, ScrollView, View } from 'react-native';

import Provider from './reducer';
import { Store } from '../../reducer';

import styles from './style';
import List from './components/List';
import Header from './components/Header';
import { TabId } from '../../constant';
import Banner from './components/Banner';
import SelectGrade from './components/SelectGrade';
import { setIsShowSelectGrade, getData, setCurrentGrade } from './actions';
import { getUserInfo } from '../../../../store/user';
import { GRADE_LIST } from './constant';

export default (): ReactElement => {
  const [refreshing, setRefreshing] = useState(false);

  const { state } = useContext(Store);
  const { currentTab } = state;

  useEffect((): void => {
    if (currentTab.id === TabId.Discovery) {
      getData();
      const { currentGrade } = getUserInfo();
      if (currentGrade) {
        const grade = GRADE_LIST.find(
          (item): boolean => item.id === currentGrade
        );
        if (grade) {
          setCurrentGrade(grade);
        }
      } else {
        setIsShowSelectGrade(true);
      }
    } else {
      setIsShowSelectGrade(false);
    }
  }, [currentTab.id]);

  return (
    <Provider>
      <View style={styles.container}>
        <ScrollView
          style={styles.scroll}
          contentContainerStyle={styles.content}
          showsVerticalScrollIndicator={false}
          refreshControl={
            <RefreshControl
              onRefresh={(): void => {
                setRefreshing(true);
                getData().then((): void => {
                  setRefreshing(false);
                });
              }}
              refreshing={refreshing}
            />
          }
        >
          <Banner />
          <List />
        </ScrollView>
        <Header />
      </View>
      <SelectGrade />
    </Provider>
  );
};
